home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / CUGUK / COMMS / C100.ZIP / KERMIT.ZIP / CKUFIO.C < prev    next >
Text File  |  1990-01-31  |  31KB  |  1,094 lines

  1. char *ckzv = "Unix file support, 4E(037) 27 Jan 88";
  2.  
  3. /* C K U F I O  --  Kermit file system support for Unix systems */
  4.  
  5. /* 4E, conditionals added for Apollo Aegis. */
  6.  
  7. /*
  8.  Author: Frank da Cruz (SY.FDC@CU20B),
  9.  Columbia University Center for Computing Activities, January 1985.
  10.  Copyright (C) 1985, Trustees of Columbia University in the City of New York.
  11.  Permission is granted to any individual or institution to use, copy, or
  12.  redistribute this software so long as it is not sold for profit, provided this
  13.  copyright notice is retained.
  14. */
  15. /* Includes */
  16.  
  17. #include <sys/types.h>            /* Data types */
  18. #include "ckcker.h"            /* Kermit definitions */
  19. #include "ckcdeb.h"            /* Typedefs, debug formats, etc */
  20. #include <ctype.h>            /* Character types */
  21. #include <stdio.h>            /* Standard i/o */
  22. #include <sys/dir.h>            /* Directory structure */
  23. #include <pwd.h>            /* Password file for shell name */
  24.  
  25. #ifdef CIE
  26. #include <stat.h>            /* File status */
  27. #else
  28. #include <sys/stat.h>
  29. #endif
  30.  
  31.  
  32. /* Berkeley Unix Version 4.x */
  33. /* 4.1bsd support added by Charles E Brooks, EDN-VAX */
  34.  
  35. #ifdef BSD4
  36. #ifdef MAXNAMLEN
  37. #define BSD42
  38. char *ckzsys = " 4.2 BSD";
  39. #else
  40. #ifdef FT18
  41. #define BSD41
  42. char *ckzsys = " Fortune For:Pro 1.8";
  43. #else
  44. #define BSD41
  45. char *ckzsys = " 4.1 BSD";
  46. #endif
  47. #endif
  48. #endif
  49.  
  50. /* 2.9bsd support contributed by Bradley Smith, UCLA */
  51. #ifdef BSD29
  52. char *ckzsys = " 2.9 BSD";
  53. #endif
  54.  
  55. /* Version 7 Unix  */
  56. #ifdef V7
  57. char *ckzsys = " Version 7 Unix";
  58. #endif
  59.  
  60. /* DEC Professional-300 series with Venturcom Venix v1 */
  61. #ifdef PROVX1
  62. char *ckzsys = " DEC Pro-3xx/Venix v1";
  63. #endif
  64.  
  65. /* NCR Tower support contributed by John Bray, Auburn, AL. */
  66. /* Tower OS is like Sys III but with BSD features -- mostly follows BSD. */
  67. #ifdef TOWER1
  68. char *ckzsys = " NCR Tower 1632, OS 1.02";
  69. #endif
  70.  
  71. /* Sys III/V, Xenix, PC/IX,... support by Herm Fischer, Litton Data Systems */
  72. #ifdef UXIII
  73. #ifdef XENIX
  74. char *ckzsys = " Xenix/286";
  75. #else
  76. #ifdef PCIX
  77. char *ckzsys = " PC/IX";
  78. #else
  79. #ifdef ISIII
  80. char *ckzsys = " Interactive Systems Corp, System III";
  81. #else
  82. #ifdef ZILOG
  83. char *ckzsys = " Zilog S8000 Zeus 3.21+";
  84. #else
  85. char *ckzsys = " AT&T System III/System V";
  86. #endif
  87. #endif
  88. #endif
  89. #endif
  90. #endif
  91.  
  92. /* Definitions of some Unix system commands */
  93.  
  94. char *DELCMD = "rm -f ";        /* For file deletion */
  95. char *PWDCMD = "pwd ";            /* For saying where I am */
  96.  
  97. #ifdef FT18
  98. char *DIRCMD = "ls -l | more ";        /* For directory listing */
  99. char *TYPCMD = "more ";            /* For typing a file */
  100. #else
  101. char *TYPCMD = "cat ";            /* For typing a file */
  102. char *DIRCMD = "ls -l ";        /* For directory listing */
  103. #endif
  104.  
  105. #ifdef FT18
  106. #undef BSD4
  107. #endif
  108.  
  109. #ifdef BSD4
  110. char *SPACMD = "pwd ; quota ; df .";    /* Space/quota of current directory */
  111. #else
  112. #ifdef FT18
  113. char #SPACMD = "pwd ; du ; df .";
  114. #else
  115. char *SPACMD = "df ";
  116. #endif
  117. #endif
  118.  
  119. char *SPACM2 = "df ";            /* For space in specified directory */
  120.  
  121. #ifdef FT18
  122. #define BSD4
  123. #endif
  124.  
  125. #ifdef BSD4
  126. char *WHOCMD = "finger ";        /* For seeing who's logged in */
  127. #else
  128. char *WHOCMD = "who ";            /* For seeing who's logged in */
  129. #endif
  130.  
  131. /*
  132.   Functions (n is one of the predefined file numbers from ckermi.h):
  133.  
  134.    zopeni(n,name)   -- Opens an existing file for input.
  135.    zopeno(n,name)   -- Opens a new file for output.
  136.    zclose(n)        -- Closes a file.
  137.    zchin(n,&c)      -- Gets the next character from an input file.
  138.    zsout(n,s)       -- Write a null-terminated string to output file, buffered.
  139.    zsoutl(n,s)      -- Like zsout, but appends a line terminator.
  140.    zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
  141.    zchout(n,c)      -- Add a character to an output file, unbuffered.
  142.    zchki(name)      -- Check if named file exists and is readable, return size.
  143.    zchko(name)      -- Check if named file can be created.
  144.    znewn(name,s)    -- Make a new unique file name based on the given name.
  145.    zdelet(name)     -- Delete the named file.
  146.    zxpand(string)   -- Expands the given wildcard string into a list of files.
  147.    znext(string)    -- Returns the next file from the list in "string".
  148.    zxcmd(cmd)       -- Execute the command in a lower fork.
  149.    zclosf()         -- Close input file associated with zxcmd()'s lower fork.
  150.    zrtol(n1,n2)     -- Convert remote filename into local form.
  151.    zltor(n1,n2)     -- Convert local filename into remote form.
  152.    zchdir(dirnam)   -- Change working directory.
  153.    zhome()          -- Return pointer to home directory name string.
  154.    zkself()         -- Kill self, log out own job.
  155.  */
  156.  
  157. #ifdef FT18
  158. #define PROVX1
  159. #endif
  160.  
  161. /* Which systems include <sys/file.h>... */
  162. #ifndef PROVX1
  163. #ifndef aegis
  164. #ifndef CIE
  165. #ifndef XENIX
  166. /* Watch out, some versions of Xenix might need to do this include, */
  167. /* but reportedly SCO Xenix 2.2 on an 80x86 system does not. */
  168. #include <sys/file.h>            /* File access */
  169. #endif
  170. #endif
  171. #endif
  172. #endif
  173.  
  174. #ifdef FT18
  175. #undef PROVX1
  176. #endif
  177.  
  178. /* Some systems define these symbols in include files, others don't... */
  179. #ifndef R_OK
  180. #define R_OK 4                /* For access */
  181. #endif
  182.  
  183. #ifndef W_OK
  184. #define W_OK 2
  185. #endif
  186.  
  187. #ifdef PROVX1
  188. #define MAXNAMLEN DIRSIZ        /* Max file name length */
  189. #endif
  190.  
  191. #ifdef UXIII
  192. #include <fcntl.h>
  193. #define MAXNAMLEN DIRSIZ
  194. #endif
  195.  
  196. #ifndef O_RDONLY
  197. #define O_RDONLY 000
  198. #endif
  199.  
  200. #ifndef MAXNAMLEN
  201. #define MAXNAMLEN 14            /* If still not defined... */
  202. #endif
  203.  
  204. #ifdef PROVX1
  205. #define MAXWLD 50            /* Maximum wildcard filenames */
  206. #else
  207. #ifdef BSD29
  208. #define MAXWLD 50            /* Maximum wildcard filenames */
  209. #else
  210. #define MAXWLD 500
  211. #endif
  212. #endif
  213.  
  214. /* Declarations */
  215.  
  216. FILE *fp[ZNFILS] = {             /* File pointers */
  217.     NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  218.  
  219. static int pid;                    /* pid of child fork */
  220. static int fcount;            /* Number of files in wild group */
  221. static char nambuf[MAXNAMLEN+2];    /* Buffer for a filename */
  222. char *malloc(), *getenv(), *strcpy();    /* System functions */
  223. extern errno;                /* System error code */
  224.  
  225. static char *mtchs[MAXWLD],        /* Matches found for filename */
  226.      **mtchptr;                /* Pointer to current match */
  227.  
  228. /*  Z K S E L F  --  Kill Self: log out own job, if possible.  */
  229.  
  230. /* Note, should get current pid, but if your system doesn't have */
  231. /* getppid(), then just kill(0,9)...  */
  232.  
  233. zkself() {                /* For "bye", but no guarantee! */
  234. #ifdef PROVX1
  235.     return(kill(0,9));
  236. #else
  237. #ifdef V7
  238.     return(kill(0,9));
  239. #else
  240. #ifdef TOWER1
  241.     return(kill(0,9));
  242. #else
  243. #ifdef FT18
  244.     return(kill(0,9));
  245. #else
  246. #ifdef aegis
  247.     return(kill(0,9));
  248. #else
  249.     return(kill(getppid(),1));
  250. #endif
  251. #endif
  252. #endif
  253. #endif
  254. #endif
  255. }
  256.  
  257. /*  Z O P E N I  --  Open an existing file for input. */
  258.  
  259. zopeni(n,name) int n; char *name; {
  260.     debug(F111," zopeni",name,n);
  261.     debug(F101,"  fp","",(int) fp[n]);
  262.     if (chkfn(n) != 0) return(0);
  263.     if (n == ZSYSFN) {            /* Input from a system function? */
  264.         debug(F110," invoking zxcmd",name,0);
  265.     return(zxcmd(name));        /* Try to fork the command */
  266.     }
  267.     if (n == ZSTDIO) {            /* Standard input? */
  268.     if (isatty(0)) {
  269.         ermsg("Terminal input not allowed");
  270.         debug(F110,"zopeni: attempts input from unredirected stdin","",0);
  271.         return(0);
  272.     }
  273.     fp[ZIFILE] = stdin;
  274.     return(1);
  275.     }
  276.     fp[n] = fopen(name,"r");        /* Real file. */
  277.     debug(F111," zopeni", name, (int) fp[n]);
  278.     if (fp[n] == NULL) perror("zopeni");
  279.     return((fp[n] != NULL) ? 1 : 0);
  280. }
  281.  
  282. /*  Z O P E N O  --  Open a new file for output.  */
  283.  
  284. zopeno(n,name) int n; char *name; {
  285.     debug(F111," zopeno",name,n);
  286.     if (chkfn(n) != 0) return(0);
  287.     if ((n == ZCTERM) || (n == ZSTDIO)) {   /* Terminal or standard output */
  288.     fp[ZOFILE] = stdout;
  289.     debug(F101," fp[]=stdout", "", (int) fp[n]);
  290.     return(1);
  291.     }
  292.     fp[n] = fopen(name,"w");        /* A real file, try to open */
  293.     if (fp[n] == NULL) {
  294.         perror("zopeno can't open");
  295.     } else {
  296.     chown(name, getuid(), getgid());     /* In case set[gu]id */
  297.         if (n == ZDFILE) setbuf(fp[n],NULL); /* Debugging file unbuffered */
  298.     }
  299.     debug(F101, " fp[n]", "", (int) fp[n]);
  300.     return((fp[n] != NULL) ? 1 : 0);
  301. }
  302.  
  303. /*  Z C L O S E  --  Close the given file.  */
  304.  
  305. /*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */
  306.  
  307. zclose(n) int n; {
  308.     int x;
  309.     if (chkfn(n) < 1) return(0);    /* Check range of n */
  310.     if ((n == ZIFILE) && fp[ZSYSFN]) {    /* If system function */
  311.         x = zclosf();            /* do it specially */
  312.     } else {
  313.         if ((fp[n] != stdout) && (fp[n] != stdin)) x = fclose(fp[n]);
  314.     fp[n] = NULL;
  315.     }
  316.     return((x == EOF) ? -1 : 1);
  317. }
  318.  
  319. /*  Z C H I N  --  Get a character from the input file.  */
  320.  
  321. /*  Returns -1 if EOF, 0 otherwise with character returned in argument  */
  322.  
  323. zchin(n,c) int n; char *c; {
  324.     int a;
  325.     if (chkfn(n) < 1) return(-1);
  326.     a = getc(fp[n]);
  327.     if (a == EOF) return(-1);
  328.     *c = a & 0377;
  329.     return(0);
  330. }
  331.  
  332. /*  Z S O U T  --  Write a string to the given file, buffered.  */
  333.  
  334. zsout(n,s) int n; char *s; {
  335.     if (chkfn(n) < 1) return(-1);
  336.     fputs(s,fp[n]);
  337.     return(0);
  338. }
  339.  
  340. /*  Z S O U T L  --  Write string to file, with line terminator, buffered  */
  341.  
  342. zsoutl(n,s) int n; char *s; {
  343.     if (chkfn(n) < 1) return(-1);
  344.     fputs(s,fp[n]);
  345.     fputs("\n",fp[n]);
  346.     return(0);
  347. }
  348.  
  349. /*  Z S O U T X  --  Write x characters to file, unbuffered.  */
  350.  
  351. zsoutx(n,s,x) int n, x; char *s; {
  352.     if (chkfn(n) < 1) return(-1);
  353. /*  return(write(fp[n]->_file,s,x));  */
  354.     return(write(fileno(fp[n]),s,x));
  355. }
  356.  
  357.  
  358. /*  Z C H O U T  --  Add a character to the given file.  */
  359.  
  360. /*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */
  361.  
  362. zchout(n,c) int n; char c; {
  363.     if (chkfn(n) < 1) return(-1);
  364.     if (n == ZSFILE)
  365.         return(write(fileno(fp[n]),&c,1)); /* Use unbuffered for session log */
  366.     else {                /* Buffered for everything else */
  367.     if (putc(c,fp[n]) == EOF)    /* If true, maybe there was an error */
  368.         return(ferror(fp[n])?-1:0);    /* Check to make sure */
  369.     else                /* Otherwise... */
  370.         return(0);            /* There was no error. */
  371.     }
  372. }
  373.  
  374. /*  C H K F N  --  Internal function to verify file number is ok  */
  375.  
  376. /*
  377.  Returns:
  378.   -1: File number n is out of range
  379.    0: n is in range, but file is not open
  380.    1: n in range and file is open
  381. */
  382. chkfn(n) int n; {
  383.     switch (n) {
  384.     case ZCTERM:
  385.     case ZSTDIO:
  386.     case ZIFILE:
  387.     case ZOFILE:
  388.     case ZDFILE:
  389.     case ZTFILE:
  390.     case ZPFILE:
  391.     case ZSFILE:
  392.     case ZSYSFN: break;
  393.     default:
  394.         debug(F101,"chkfn: file number out of range","",n);
  395.         fprintf(stderr,"?File number out of range - %d\n",n);
  396.         return(-1);
  397.     }
  398.     return( (fp[n] == NULL) ? 0 : 1 );
  399. }
  400.  
  401. /*  Z C H K I  --  Check if input file exists and is readable  */
  402.  
  403. /*
  404.   Returns:
  405.    >= 0 if the file can be read (returns the size).
  406.      -1 if file doesn't exist or can't be accessed,
  407.      -2 if file exists but is not readable (e.g. a directory file).
  408.      -3 if file exists but protected against read access.
  409. */
  410. /*
  411.  For Berkeley Unix, a file must be of type "regular" to be readable.
  412.  Directory files, special files, and symbolic links are not readable.
  413. */
  414. long
  415. zchki(name) char *name; {
  416.     struct stat buf;
  417.     int x; long y;
  418.  
  419.     x = stat(name,&buf);
  420.     if (x < 0) {
  421.     debug(F111,"zchki stat fails",name,errno);
  422.     return(-1);
  423.     }
  424.     x = buf.st_mode & S_IFMT;        /* Isolate file format field */
  425.     if ((x != 0) && (x != S_IFREG)) {
  426.     debug(F111,"zchki skipping:",name,x);
  427.     return(-2);
  428.     }
  429.     debug(F111,"zchki stat ok:",name,x);
  430.  
  431.     if ((x = access(name,R_OK)) < 0) {     /* Is the file accessible? */
  432.     debug(F111," access failed:",name,x); /* No */
  433.         return(-3);            
  434.     } else {
  435.     y = buf.st_size;
  436.     debug(F111," access ok:",name,(int) y); /* Yes */
  437.     return( (y > -1) ? y : 0 );
  438.     }
  439. }
  440.  
  441. /*  Z C H K O  --  Check if output file can be created  */
  442.  
  443. /*
  444.  Returns -1 if write permission for the file would be denied, 0 otherwise.
  445. */
  446. zchko(name) char *name; {
  447.     int i, x;
  448.     char s[50], *sp;    
  449.  
  450.     sp = s;                /* Make a copy, get length */
  451.     x = 0;
  452.     while ((*sp++ = *name++) != '\0')
  453.         x++;
  454.     if (x == 0) return(-1);        /* If no filename, fail. */
  455.  
  456.     debug(F101," length","",x);
  457.     for (i = x; i > 0; i--)        /* Strip filename. */
  458.     if (s[i-1] == '/') break;
  459.  
  460.     debug(F101," i","",i);
  461.     if (i == 0)                /* If no path, use current directory */
  462.         strcpy(s,"./");            
  463.     else                /* Otherwise, use given one. */
  464.         s[i] = '\0';
  465.  
  466.     x = access(s,W_OK);            /* Check access of path. */
  467.     if (x < 0) {
  468.     debug(F111,"zchko access failed:",s,errno);
  469.     return(-1);
  470.     } else {
  471.     debug(F111,"zchko access ok:",s,x);
  472.     return(0);
  473.     }
  474. }
  475.  
  476. /*  Z D E L E T  --  Delete the named file.  */
  477.  
  478. zdelet(name) char *name; {
  479.     unlink(name);
  480. }
  481.  
  482.  
  483. /*  Z R T O L  --  Convert remote filename into local form  */
  484.  
  485. /*  For UNIX, this means changing uppercase letters to lowercase.  */
  486.  
  487. zrtol(name,name2) char *name, *name2; {
  488.     for ( ; *name != '\0'; name++) {
  489.         *name2++ = isupper(*name) ? tolower(*name) : *name;
  490.     }
  491.     *name2 = '\0';
  492.     debug(F110,"zrtol:",name2,0);
  493. }
  494.  
  495.  
  496. /*  Z L T O R  --  Local TO Remote */
  497.  
  498. /*  Convert filename from local format to common (remote) form.  */
  499.  
  500. zltor(name,name2) char *name, *name2; {
  501.     char work[100], *cp, *pp;
  502.     int dc = 0;
  503. #ifdef aegis
  504.     char *getenv(), *index(), *namechars;
  505.     int tilde = 0, bslash = 0;
  506.  
  507.     if ((namechars = getenv("NAMECHARS")) != NULL) {
  508.         if (index(namechars, '~' ) != NULL) tilde  = '~';
  509.         if (index(namechars, '\\') != NULL) bslash = '\\';
  510.     } else {
  511.         tilde = '~';
  512.         bslash = '\\';
  513.     }
  514. #endif
  515.  
  516.     debug(F110,"zltor",name,0);
  517.     pp = work;
  518. #ifdef aegis
  519.     cp = name;
  520.     if (tilde && *cp == tilde)
  521.         ++cp;
  522.     for (; *cp != '\0'; cp++) {    /* strip path name */
  523.         if (*cp == '/' || *cp == bslash) {
  524. #else
  525.     for (cp = name; *cp != '\0'; cp++) {    /* strip path name */
  526.         if (*cp == '/') {
  527. #endif
  528.         dc = 0;
  529.         pp = work;
  530.     }
  531.     else if (islower(*cp)) *pp++ = toupper(*cp); /* Uppercase letters */
  532.     else if (*cp == '~') *pp++ = 'X';    /* Change tilde to 'X' */
  533.     else if (*cp == '#') *pp++ = 'X';    /* Change number sign to 'X' */
  534.     else if ((*cp == '.') && (++dc > 1)) *pp++ = 'X'; /* & extra dots */
  535.     else *pp++ = *cp;
  536.     }
  537.     *pp = '\0';                /* Tie it off. */
  538.     cp = name2;                /* If nothing before dot, */
  539.     if (*work == '.') *cp++ = 'X';    /* insert 'X' */
  540.     strcpy(cp,work);
  541.     debug(F110," name2",name2,0);
  542. }
  543.  
  544.  
  545. /*  Z C H D I R  --  Change directory  */
  546.  
  547. zchdir(dirnam) char *dirnam; {
  548.     char *hd;
  549.     if (*dirnam == '\0') hd = getenv("HOME");
  550.     else hd = dirnam;
  551.     return((chdir(hd) == 0) ? 1 : 0);
  552. }
  553.  
  554.  
  555. /*  Z H O M E  --  Return pointer to user's home directory  */
  556.  
  557. char *
  558. zhome() {
  559.     return(getenv("HOME"));
  560. }
  561.  
  562. /*  Z G T D I R  --  Return pointer to user's current directory  */
  563.  
  564. char *
  565. zgtdir() {
  566.  
  567. #ifdef MAXPATHLEN
  568. #define CWDBL MAXPATHLEN
  569. #else
  570. #define CWDBL 100
  571. #endif
  572.  
  573. #ifdef UXIII
  574.     char cwdbuf[CWDBL+1];
  575.     char *buf;
  576.     char *getcwd();
  577.     buf = cwdbuf;
  578.     return(getcwd(buf,CWDBL));
  579. #else
  580. #ifdef BSD4
  581.     char cwdbuf[CWDBL+1];
  582.     char *buf;
  583.     char *getwd();
  584.     buf = cwdbuf;
  585.     return(getwd(buf));
  586. #else
  587.     return("(directory unknown)");
  588. #endif
  589. #endif
  590. }
  591.  
  592. /*  Z X C M D -- Run a system command so its output can be read like a file */
  593.  
  594. zxcmd(comand) char *comand; {
  595.     int pipes[2];
  596.     if (pipe(pipes) != 0) {
  597.     debug(F100,"zxcmd pipe failure","",0);
  598.     return(0);            /* can't make pipe, fail */
  599.     }
  600. #ifdef aegis
  601.     if ((pid = vfork()) == 0) {        /* child */
  602. #else
  603.     if ((pid = fork()) == 0) {        /* child */
  604. #endif
  605.  
  606.  
  607. /*#if BSD4*/        /* Code from Dave Tweten@AMES-NAS */
  608.             /* readapted to use getpwuid to find login shell */
  609.             /*   -- H. Fischer */
  610.     char *shpath, *shname, *shptr;    /* to find desired shell */
  611. #ifndef aegis
  612.     struct passwd *p;
  613.     extern struct passwd * getpwuid();
  614.     extern int getuid();
  615.     char *defShel = "/bin/sh";    /* default shell */
  616. #endif
  617.  
  618.     close(pipes[0]);        /* close input side of pipe */
  619.     close(0);            /* close stdin */
  620.     if (open("/dev/null",0) < 0) return(0);    /* replace input by null */
  621.  
  622. #ifndef UXIII
  623.     dup2(pipes[1],1);        /* replace stdout & stderr */
  624.     dup2(pipes[1],2);        /* by the pipe */
  625. #else
  626.     close(1);            /* simulate dup2 */
  627.     if (dup(pipes[1]) != 1 )
  628.         conol("trouble duping stdout in routine zxcmd\n");
  629.     close(2);            /* simulate dup2 */
  630.     if (dup(pipes[1]) != 2 )
  631.         conol("trouble duping stderr in routine zxcmd\n");
  632. #endif
  633.  
  634.     close(pipes[1]);        /* get rid of this copy of the pipe */
  635.  
  636. #ifdef aegis
  637.     if ((shpath = getenv("SERVERSHELL")) == NULL) shpath = "/bin/sh";
  638. #else
  639.  
  640. /****     shptr = shname = shpath = getenv("SHELL");  /* What shell? */
  641.     p = getpwuid( getuid() );    /* get login data */
  642.     if ( p == (struct passwd *) NULL || !*(p->pw_shell) ) shpath = defShel;
  643.       else shpath = p->pw_shell;
  644. #endif
  645.     shptr = shname = shpath;
  646.     while (*shptr != '\0') if (*shptr++ == '/') shname = shptr;
  647.     debug(F100,"zxcmd...","",0);
  648.     debug(F110,shpath,shname,0);
  649.  
  650. /* Remove the following uid calls if they cause trouble... */
  651. #ifdef BSD4
  652.     setegid(getgid());        /* Override 4.3BSD csh */
  653.     seteuid(getuid());        /*  security checks */
  654. #endif /* bsd4 */
  655.  
  656.     execl(shpath,shname,"-c",comand,(char *)NULL); /* Execute the cmd */
  657.     exit(0);            /* just punt if it failed. */
  658.     } else if (pid == -1) {
  659.     debug(F100,"zxcmd fork failure","",0);
  660.     return(0);
  661.     }
  662.     close(pipes[1]);            /* don't need the output side */
  663.     fp[ZIFILE] = fdopen(pipes[0],"r");    /* open a stream for it */
  664.     fp[ZSYSFN] = fp[ZIFILE];        /* Remember. */
  665.     return(1);
  666. }
  667.  
  668. /*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */
  669.  
  670. zclosf() {
  671.     int wstat;
  672.     if (kill(pid,9) == 0) {
  673.     debug(F101,"zclosf pid =","",pid);
  674.         while ((wstat = wait((int *)0)) != pid && wstat != -1) ;
  675.         pid = 0;
  676.     }
  677.     fclose(fp[ZIFILE]);
  678.     fp[ZIFILE] = fp[ZSYSFN] = NULL;
  679.     return(1);
  680. }
  681.  
  682. /*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
  683. /*
  684.   Returns the number of files that match fn1, with data structures set up
  685.   so that first file (if any) will be returned by the next znext() call.
  686. */
  687. zxpand(fn) char *fn; {
  688.     fcount = fgen(fn,mtchs,MAXWLD);    /* Look up the file. */
  689.     if (fcount > 0) {
  690.     mtchptr = mtchs;        /* Save pointer for next. */
  691.     }
  692.     debug(F111,"zxpand",mtchs[0],fcount);
  693.     return(fcount);
  694. }
  695.  
  696.  
  697. /*  Z N E X T  --  Get name of next file from list created by zxpand(). */
  698. /*
  699.  Returns >0 if there's another file, with its name copied into the arg string,
  700.  or 0 if no more files in list.
  701. */
  702. znext(fn) char *fn; {
  703.     if (fcount-- > 0) strcpy(fn,*mtchptr++);
  704.     else *fn = '\0';
  705.     debug(F111,"znext",fn,fcount+1);
  706.     return(fcount+1);
  707. }
  708.  
  709.  
  710. /*  Z N E W N  --  Make a new name for the given file  */
  711.  
  712. znewn(fn,s) char *fn, **s; {
  713. #ifdef BSD4
  714.     static char buf[256];
  715. #else
  716.     static char buf[100];
  717. #endif
  718.     char *bp, *xp;
  719.     int len = 0, n = 0, d = 0, t, i, power = 1;
  720. #ifdef MAXNAMLEN
  721.     int max = MAXNAMLEN;
  722. #else
  723.     int max = 14;
  724. #endif
  725.     bp = buf;
  726.     while (*fn) {            /* Copy name into buf */
  727.     *bp++ = *fn++;
  728.     len++;
  729.     }
  730.     if (len > max-2) {             /* Don't let it get too long */
  731.     bp = buf + max-2;
  732.     len = max - 2;
  733.     }
  734.     
  735.     for (i = 1; i < 4; i++) {        /* Try up to 999 times */
  736.     power *= 10;
  737.     *bp++ = '*';            /* Put a star on the end */
  738.     *bp-- = '\0';
  739.     
  740.     n = zxpand(buf);        /* Expand the resulting wild name */
  741.  
  742.     while (n-- > 0) {        /* Find any existing name~d files */
  743.         xp = *mtchptr++;
  744.         xp += len;
  745.         if (*xp == '~') {
  746.         t = atoi(xp+1);
  747.         if (t > d) d = t;    /* Get maximum d */
  748.         }
  749.     }
  750.     if (d < power-1) {
  751.         sprintf(bp,"~%d",d+1);    /* Make name~(d+1) */
  752.         *s = buf;
  753.         return;
  754.     }
  755.     bp--; len--;
  756.     }
  757. /* If we ever get here, we'll overwrite the xxx~100 file... */
  758. }
  759.  
  760. /* Directory Functions for Unix, written by Jeff Damens, CUCCA, 1984. */
  761.  
  762. /*
  763.  * The path structure is used to represent the name to match.
  764.  * Each slash-separated segment of the name is kept in one
  765.  * such structure, and they are linked together, to make
  766.  * traversing the name easier.
  767.  */
  768.  
  769. struct path {
  770.               char npart[MAXNAMLEN];    /* name part of path segment */
  771.               struct path *fwd;        /* forward ptr */
  772.             };
  773.  
  774. #ifdef PROVX1
  775. #define SSPACE 500
  776. #else
  777. #ifdef BSD29
  778. #define SSPACE 500
  779. #else
  780. #ifdef aegis
  781. #define SSPACE 10000            /* size of string-generating buffer */
  782. static char bslash;            /* backslash character if active */
  783. #else
  784. #define SSPACE 2000            /* size of string-generating buffer */
  785. #endif
  786. #endif
  787. #endif
  788. static char sspace[SSPACE];             /* buffer to generate names in */
  789. static char *freeptr,**resptr;             /* copies of caller's arguments */
  790. static int remlen;                      /* remaining length in caller's array*/
  791. static int numfnd;                      /* number of matches found */
  792.  
  793. /*
  794.  * splitpath:
  795.  *  takes a string and splits the slash-separated portions into
  796.  *  a list of path structures.  Returns the head of the list.  The
  797.  *  structures are allocated by malloc, so they must be freed.
  798.  *  Splitpath is used internally by the filename generator.
  799.  *
  800.  * Input: A string.
  801.  * Returns: A linked list of the slash-separated segments of the input.
  802.  */
  803.  
  804. struct path *
  805. splitpath(p)
  806. char *p;
  807. {
  808.  struct path *head,*cur,*prv;
  809.  int i;
  810.  head = prv = NULL;
  811.  if (*p == '/') p++;            /* skip leading slash */
  812.  while (*p != '\0')
  813.  {
  814.    cur = (struct path *) malloc(sizeof (struct path));
  815.    debug(F101,"splitpath malloc","",cur);
  816.    if (cur == NULL) fatal("malloc fails in splitpath()");
  817.    cur -> fwd = NULL;
  818.    if (head == NULL) head = cur;
  819.    else prv -> fwd = cur;       /* link into chain */
  820.    prv = cur;
  821. #ifdef aegis
  822.    /* treat backslash as "../" */
  823.    if (bslash && *p == bslash) {
  824.      strcpy(cur->npart, "..");
  825.      ++p;
  826.    } else {
  827.      for (i=0; i < MAXNAMLEN && *p && *p != '/' && *p != bslash; i++)
  828.        cur -> npart[i] = *p++;
  829.      cur -> npart[i] = '\0';      /* end this segment */
  830.      if (i >= MAXNAMLEN) while (*p && *p != '/' && *p != bslash) p++;
  831.    }
  832.    if (*p == '/') p++;
  833. #else
  834.    for (i=0; i < MAXNAMLEN && *p != '/' && *p != '\0'; i++)
  835.      cur -> npart[i] = *p++;
  836.    cur -> npart[i] = '\0';      /* end this segment */
  837.    if (i >= MAXNAMLEN) while (*p != '/' && *p != '\0') p++;
  838.    if (*p == '/') p++;
  839. #endif
  840.  }
  841.  return(head);
  842. }
  843.  
  844. /*
  845.  * fgen:
  846.  *  This is the actual name generator.  It is passed a string,
  847.  *  possibly containing wildcards, and an array of character pointers.
  848.  *  It finds all the matching filenames and stores them into the array.
  849.  *  The returned strings are allocated from a static buffer local to
  850.  *  this module (so the caller doesn't have to worry about deallocating
  851.  *  them); this means that successive calls to fgen will wipe out
  852.  *  the results of previous calls.  This isn't a problem here
  853.  *  because we process one wildcard string at a time.
  854.  *
  855.  * Input: a wildcard string, an array to write names to, the
  856.  *        length of the array.
  857.  * Returns: the number of matches.  The array is filled with filenames
  858.  *          that matched the pattern.  If there wasn't enough room in the
  859.  *        array, -1 is returned.
  860.  * By: Jeff Damens, CUCCA, 1984.
  861.  */
  862.  
  863. fgen(pat,resarry,len)
  864. char *pat,*resarry[];
  865. int len;
  866. {
  867.  struct path *head;
  868.  char scratch[100],*sptr;
  869. #ifdef aegis
  870.  char *getenv(), *index(), *namechars;
  871.  int tilde = 0, bquote = 0;
  872.  
  873.  if ((namechars = getenv("NAMECHARS")) != NULL) {
  874.   if (index(namechars, '~' ) != NULL) tilde  = '~';
  875.   if (index(namechars, '\\') != NULL) bslash = '\\';
  876.   if (index(namechars, '`' ) != NULL) bquote = '`';
  877.  }
  878.  else { tilde = '~'; bslash = '\\'; bquote = '`'; }
  879.  
  880.  sptr = scratch;
  881.  /* copy "`node_data", etc. anchors */
  882.  if (bquote && *pat == bquote)
  883.   while (*pat && *pat != '/' && *pat != bslash)
  884.    *sptr++ = *pat++;
  885.  else if (tilde && *pat == tilde)
  886.   *sptr++ = *pat++;
  887.  while (*pat == '/')
  888.   *sptr++ = *pat++;
  889.  if (sptr == scratch)
  890.  {
  891.   strcpy(scratch,"./");
  892.   sptr = scratch+2;
  893.  }                    /* init buffer correctly */
  894.  head = splitpath(pat);
  895. #else
  896.  head = splitpath(pat);
  897.  if (*pat == '/')
  898.  {
  899.   scratch[0] = '/';
  900.   sptr = scratch+1;
  901.  }
  902.  else
  903.  {
  904.   strcpy(scratch,"./");
  905.   sptr = scratch+2;
  906.  }                    /* init buffer correctly */
  907. #endif
  908.  numfnd = 0;                            /* none found yet */
  909.  freeptr = sspace;            /* this is where matches are copied */
  910.  resptr = resarry;            /* static copies of these so*/
  911.  remlen = len;                /* recursive calls can alter them */
  912.  traverse(head,scratch,sptr);        /* go walk the directory tree */
  913.  for (; head != NULL; head = head -> fwd)
  914.    free(head);                /* return the path segments */
  915.  return(numfnd);            /* and return the number of matches */
  916. }
  917.  
  918. /* traverse:
  919.  *  Walks the directory tree looking for matches to its arguments.
  920.  *  The algorithm is, briefly:
  921.  *   If the current pattern segment contains no wildcards, that
  922.  *   segment is added to what we already have.  If the name so far
  923.  *   exists, we call ourselves recursively with the next segment
  924.  *   in the pattern string; otherwise, we just return.
  925.  *
  926.  *   If the current pattern segment contains wildcards, we open the name
  927.  *   we've accumulated so far (assuming it is really a directory), then read
  928.  *   each filename in it, and, if it matches the wildcard pattern segment, add
  929.  *   that filename to what we have so far and call ourselves recursively on the
  930.  *   next segment.
  931.  *
  932.  *   Finally, when no more pattern segments remain, we add what's accumulated
  933.  *   so far to the result array and increment the number of matches.
  934.  *
  935.  * Input: a pattern path list (as generated by splitpath), a string
  936.  *      pointer that points to what we've traversed so far (this
  937.  *      can be initialized to "/" to start the search at the root
  938.  *      directory, or to "./" to start the search at the current
  939.  *      directory), and a string pointer to the end of the string
  940.  *      in the previous argument.
  941.  * Returns: nothing.
  942.  */
  943. traverse(pl,sofar,endcur)
  944. struct path *pl;
  945. char *sofar,*endcur;
  946. {
  947. #ifdef BSD42
  948.  DIR *fd, *opendir();
  949.  struct direct *dirbuf;
  950. #else
  951. #ifdef BSD29
  952.  DIR *fd, *opendir();
  953.  struct direct *dirbuf;
  954. #else
  955.  int fd;
  956.  struct direct dir_entry;
  957.  struct direct *dirbuf = &dir_entry;
  958. #endif
  959. #endif
  960.  struct stat statbuf;
  961.  if (pl == NULL)
  962.  {
  963.   *--endcur = '\0';                    /* end string, overwrite trailing / */
  964.   addresult(sofar);
  965.   return;
  966.  }
  967.  if (!iswild(pl -> npart))
  968.  {
  969.   strcpy(endcur,pl -> npart);
  970.   endcur += strlen(pl -> npart);
  971.   *endcur = '\0';                         /* end current string */
  972.   if (stat(sofar,&statbuf) == 0)    /* if current piece exists */
  973.   {
  974.       *endcur++ = '/';                  /* add slash to end */
  975.       *endcur = '\0';            /* and end the string */
  976.       traverse(pl -> fwd,sofar,endcur);
  977.   }
  978.   return;
  979.  }
  980. /* cont'd... */
  981.  
  982. /*...traverse, cont'd */
  983.  
  984. /* segment contains wildcards, have to search directory */
  985.  *endcur = '\0';                            /* end current string */
  986.  if (stat(sofar,&statbuf) == -1) return;       /* doesn't exist, forget it */
  987.  if ((statbuf.st_mode & S_IFDIR) == 0) return;  /* not a directory, skip */
  988. #ifdef BSD42            /* ==BSD4 */
  989.  if ((fd = opendir(sofar)) == NULL) return;      /* can't open, forget it */
  990.  while (dirbuf = readdir(fd))
  991. #else
  992. #ifdef BSD29            /* ==BSD29 */
  993.  if ((fd = opendir(sofar)) == NULL) return;      /* can't open, forget it */
  994.  while (dirbuf = readdir(fd))
  995. #else
  996.  
  997.  if ((fd = open(sofar,O_RDONLY)) < 0) return;      /* can't open, forget it */
  998.  while ( read(fd,dirbuf,sizeof dir_entry) )
  999. #endif
  1000. #endif
  1001. {
  1002.   strncpy(nambuf,dirbuf->d_name,MAXNAMLEN); /* Get a null terminated copy!!! */
  1003.   nambuf[MAXNAMLEN] = '\0';
  1004.   if (dirbuf->d_ino != 0 && match(pl -> npart,nambuf)) {
  1005.     char *eos;
  1006.     strcpy(endcur,nambuf);
  1007.     eos = endcur + strlen(nambuf);
  1008.     *eos = '/';                    /* end this segment */
  1009.     traverse(pl -> fwd,sofar,eos+1);
  1010.   }
  1011. }
  1012. #ifdef BSD42            /* ==BSD4 */
  1013.  closedir(fd);
  1014. #else
  1015. #ifdef BSD29
  1016.  closedir(fd);
  1017. #else
  1018.  close(fd);
  1019. #endif
  1020. #endif
  1021. }
  1022.  
  1023. /*
  1024.  * addresult:
  1025.  *  Adds a result string to the result array.  Increments the number
  1026.  *  of matches found, copies the found string into our string
  1027.  *  buffer, and puts a pointer to the buffer into the caller's result
  1028.  *  array.  Our free buffer pointer is updated.  If there is no
  1029.  *  more room in the caller's array, the number of matches is set to -1.
  1030.  * Input: a result string.
  1031.  * Returns: nothing.
  1032.  */
  1033.  
  1034. addresult(str)
  1035. char *str;
  1036. {
  1037.  int l;
  1038.  if (strncmp(str,"./",2) == 0) str += 2;
  1039.  if (--remlen < 0) {
  1040.   numfnd = -1;
  1041.   return;
  1042.  }
  1043.  l = strlen(str) + 1;            /* size this will take up */
  1044.  if ((freeptr + l) > &sspace[SSPACE-1]) {
  1045.     numfnd = -1;            /* do not record if not enough space */
  1046.     return;
  1047.   }
  1048.  strcpy(freeptr,str);
  1049.  *resptr++ = freeptr;
  1050.  freeptr += l;
  1051.  numfnd++;
  1052. }
  1053.  
  1054. iswild(str)
  1055. char *str;
  1056. {
  1057.  char c;
  1058.  while ((c = *str++) != '\0')
  1059.    if (c == '*' || c == '?') return(1);
  1060.  return(0);
  1061. }
  1062.  
  1063. /*
  1064.  * match:
  1065.  *  pattern matcher.  Takes a string and a pattern possibly containing
  1066.  *  the wildcard characters '*' and '?'.  Returns true if the pattern
  1067.  *  matches the string, false otherwise.
  1068.  * by: Jeff Damens, CUCCA
  1069.  *
  1070.  * Input: a string and a wildcard pattern.
  1071.  * Returns: 1 if match, 0 if no match.
  1072.  */
  1073.  
  1074. match(pattern,string) char *pattern,*string; {
  1075.     char *psave,*ssave;            /* back up pointers for failure */
  1076.     psave = ssave = NULL;
  1077.     while (1) {
  1078.     for (; *pattern == *string; pattern++,string++)  /* skip first */
  1079.         if (*string == '\0') return(1);    /* end of strings, succeed */
  1080.     if (*string != '\0' && *pattern == '?') {
  1081.         pattern++;            /* '?', let it match */
  1082.         string++;
  1083.     } else if (*pattern == '*') {    /* '*' ... */
  1084.         psave = ++pattern;        /* remember where we saw it */
  1085.         ssave = string;        /* let it match 0 chars */
  1086.     } else if (ssave != NULL && *ssave != '\0') {    /* if not at end  */
  1087.                       /* ...have seen a star */
  1088.         string = ++ssave;        /* skip 1 char from string */
  1089.         pattern = psave;        /* and back up pattern */
  1090.     } else return(0);        /* otherwise just fail */
  1091.     }
  1092. }
  1093.  
  1094.